package jp.tonosama.komoki.SimpleGolfScorer2;

import java.util.Calendar;

import jp.tonosama.komoki.SimpleGolfScorer2.data.GolfScoreData;
import jp.tonosama.komoki.SimpleGolfScorer2.history.GolfScoreManager;
import jp.tonosama.komoki.SimpleGolfScorer2.main.MainGolfScorer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * @author Komoki
 */
public class NewCreate extends Activity {

    /**  */
    private static final String TAG = NewCreate.class.getSimpleName();
    /**  */
    private static final String[] PREF_DATA_KEY = Util.PREF_DATA_KEY;
    /**  */
    private int mSavedNumber;
    /**  */
    private int mPlayerNum = 2;
    /**  */
    private boolean mIsNewCreate;
    /**  */
    private boolean mIsMemoVisible = true;
    /**  */
    private String mHoleTitle;
    /**  */
    private int mRoundCondit = 0;
    /**  */
    private Spinner mConditionSpinner;
    /**  */
    private String mMemoText;
    /**  */
    private String mPersonHandi = "0,0,0,0";
    /**  */
    private boolean mIsDeleted = false;
    /**  */
    private String[] mPersonNames = new String[Util.MAX_PLAYER_NUM];
    /**  */
    private boolean mIs18hRound = true;

    /**  */
    private EditText mTitleEdit;
    /**  */
    private EditText[] mPlayerEdit = new EditText[Util.MAX_PLAYER_NUM];
    /**  */
    private EditText[] mHandicEdit = new EditText[Util.MAX_PLAYER_NUM];
    /**  */
    private EditText mMemoEdit;
    /**  */
    private Button mStartButton;
    /**  */
    private ImageButton mPlayerAddButton;
    /**  */
    private ImageButton[] mPlayerDelButton = new ImageButton[Util.MAX_PLAYER_NUM];
    /**  */
    private final int[] mPlayerDelButtonRes = { R.id.per1_del_button, R.id.per2_del_button,
            R.id.per3_del_button, R.id.per4_del_button };
    /**  */
    private ViewGroup[] mPlayerEditArea = new ViewGroup[Util.MAX_PLAYER_NUM];
    /**  */
    private final int[] mPlayerEditAreaRes = { R.id.per1_name_edit_area, R.id.per2_name_edit_area,
            R.id.per3_name_edit_area, R.id.per4_name_edit_area };
    /**  */
    private RadioGroup mRadioGroup;
    /**  */
    private CheckBox mIsShortCheck;
    /**  */
    private ImageButton mMemoToggleButton;
    /**  */
    private ImageButton mMainExitButton;

    public void findAllViews() {
        mTitleEdit = (EditText) findViewById(R.id.hole_title_editor);
        mPlayerEdit[0] = (EditText) findViewById(R.id.per1_name_editor);
        mPlayerEdit[1] = (EditText) findViewById(R.id.per2_name_editor);
        mPlayerEdit[2] = (EditText) findViewById(R.id.per3_name_editor);
        mPlayerEdit[3] = (EditText) findViewById(R.id.per4_name_editor);

        mHandicEdit[0] = ((EditText) findViewById(R.id.per1_handi));
        mHandicEdit[1] = ((EditText) findViewById(R.id.per2_handi));
        mHandicEdit[2] = ((EditText) findViewById(R.id.per3_handi));
        mHandicEdit[3] = ((EditText) findViewById(R.id.per4_handi));

        for (int i = 0; i < Util.MAX_PLAYER_NUM; i++) {
            mPlayerEditArea[i] = (ViewGroup) findViewById(mPlayerEditAreaRes[i]);
            mPlayerDelButton[i] = (ImageButton) findViewById(mPlayerDelButtonRes[i]);
        }

        mMemoEdit = (EditText) findViewById(R.id.memo_editor_area);
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_group);
        mIsShortCheck = ((CheckBox) findViewById(R.id.chck_short_setting));
        mConditionSpinner = (Spinner) findViewById(R.id.round_condition);

        mPlayerAddButton = (ImageButton) findViewById(R.id.player_add_button);
        mStartButton = (Button) findViewById(R.id.exit_setting);
        mMemoToggleButton = (ImageButton) findViewById(R.id.memo_toggle_button);
        mMainExitButton = (ImageButton) findViewById(R.id.main_exit_button);
    }

    @Override
    public void onCreate(final Bundle icicle) {
        super.onCreate(icicle);

        if (GolfScoreManager.DEBUG) {
            Log.d(TAG, "onCreate -> s");
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.new_create);

        findAllViews();

        Bundle extras = getIntent().getExtras();
        mIsNewCreate = extras.getBoolean("NEW_CREATE");
        mSavedNumber = extras.getInt("SAVED_NUMBER");
        mPlayerNum = extras.getInt("PLAYER_NUM");

        if (mIsNewCreate) {
            setupInitialValue(extras);
        } else {
            setupSavedValue(extras);
        }
        for (int i = 0; i < Util.MAX_PLAYER_NUM; i++) {
            if (i < mPlayerNum) {
                mPlayerEditArea[i].setVisibility(View.VISIBLE);
            } else {
                mPlayerEditArea[i].setVisibility(View.GONE);
            }
        }

        setupRoundConditSpinner(extras.getInt("ROUND_CONDIT"));

        setupButtonAction();

        if (GolfScoreManager.DEBUG) {
            Log.d(TAG, "onCreate -> e");
        }
    }

    /**
     * @param extras バンドル
     */
    private void setupInitialValue(final Bundle extras) {

        String myName = extras.getString("MY_NAME");
        mPlayerEdit[0].setText(myName);
        Calendar calendar = Calendar.getInstance();
        String nowDate = "";
        nowDate += String.valueOf(calendar.get(Calendar.YEAR)) + "/";
        nowDate += String.valueOf(calendar.get(Calendar.MONTH) + 1) + "/";
        nowDate += String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)) + " ";
        mTitleEdit.setText(nowDate);
        mRadioGroup.check(R.id.radio_edit_18h);
        mIsShortCheck.setChecked(false);
    }

    /**
     * @param extras バンドル
     */
    private void setupSavedValue(final Bundle extras) {

        mTitleEdit.setText(extras.getString("HOLE_TITLE"));
        mPlayerEdit[0].setText(extras.getString("PERSON_NAME1"));
        mPlayerEdit[1].setText(extras.getString("PERSON_NAME2"));
        mPlayerEdit[2].setText(extras.getString("PERSON_NAME3"));
        mPlayerEdit[3].setText(extras.getString("PERSON_NAME4"));
        mMemoEdit.setText(extras.getString("MEMO_TEXT"));
        mHandicEdit[0].setText(String.valueOf(extras.getIntArray("PERSON_HANDI")[0]));
        mHandicEdit[1].setText(String.valueOf(extras.getIntArray("PERSON_HANDI")[1]));
        mHandicEdit[2].setText(String.valueOf(extras.getIntArray("PERSON_HANDI")[2]));
        mHandicEdit[3].setText(String.valueOf(extras.getIntArray("PERSON_HANDI")[3]));
        mIs18hRound = extras.getBoolean("IS_18H_ROUND");
        if (mIs18hRound) {
            mRadioGroup.check(R.id.radio_edit_18h);
        } else {
            mRadioGroup.check(R.id.radio_edit_outin);
        }
        boolean isShortHole = false;
        int[] parScore = extras.getIntArray("PAR_SCORE");
        if (parScore != null) {
            isShortHole = true;
            for (int i = 0; i < parScore.length; i++) {
                if (parScore[i] != 3) {
                    isShortHole = false;
                }
            }
        }
        mIsShortCheck.setChecked(isShortHole);
    }

    /**
     * @param roundCondit ラウンド条件
     */
    private void setupRoundConditSpinner(final int roundCondit) {

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner);
        adapter.setDropDownViewResource(R.layout.spinner_dropdown);
        adapter.add(getResources().getString(R.string.weather_shine));
        adapter.add(getResources().getString(R.string.weather_cloudy));
        adapter.add(getResources().getString(R.string.weather_rain));
        adapter.add(getResources().getString(R.string.weather_wind));
        adapter.add(getResources().getString(R.string.weather_mud));
        mConditionSpinner.setPrompt(getResources().getString(R.string.weather_select_title));
        mConditionSpinner.setAdapter(adapter);
        if (!mIsNewCreate) {
            mRoundCondit = roundCondit;
            mConditionSpinner.setSelection(mRoundCondit);
        }
    }

    /**
     * ラジオボタン押下時の動作
     * 
     * @param group ラジオボタン
     */
    private void setupRadioButtonAction(final RadioGroup group) {

        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            public void onCheckedChanged(final RadioGroup group, final int checkedId) {
                if (checkedId == R.id.radio_edit_18h) {
                    mIs18hRound = true;
                }
                if (checkedId == R.id.radio_edit_outin) {
                    mIs18hRound = false;
                }
            }
        });
    }

    /**
     * プレイヤー追加ボタン押下時の動作
     * 
     * @param button プレイヤー追加ボタン
     */
    private void setupPlayerAddButtonAction(final ImageButton button) {

        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(final View v) {
                if (mPlayerNum < Util.MAX_PLAYER_NUM) {
                    mPlayerNum++;
                    for (int i = 0; i < Util.MAX_PLAYER_NUM; i++) {
                        if (i < mPlayerNum) {
                            mPlayerEditArea[i].setVisibility(View.VISIBLE);
                        } else {
                            mPlayerEditArea[i].setVisibility(View.GONE);
                        }
                    }
                }
                if (mPlayerNum == Util.MAX_PLAYER_NUM) {
                    button.setImageResource(R.drawable.image_button_add_disable);
                    button.setEnabled(false);
                }
                return;
            }
        });
    }

    /**
     * プレイヤー削除ボタン押下時の動作
     * 
     * @param button プレイヤー削除ボタン
     */
    private void setupPlayerDeleteButtonAction(final ImageButton[] button) {

        for (int i = 0; i < Util.MAX_PLAYER_NUM; i++) {
            button[i].setOnClickListener(new View.OnClickListener() {

                public void onClick(final View v) {
                    int j = 0;
                    for (j = 0; j < Util.MAX_PLAYER_NUM; j++) {
                        if (v == button[j]) {
                            break;
                        }
                    }
                    final int pressedNum = j;
                    if (mIsNewCreate || mPlayerEdit[j].getText().toString().trim().length() == 0) {
                        mPlayerEdit[j].setText("");
                        for (int i = j + 1; i < mPlayerNum; i++) {
                            mPlayerEdit[i - 1].setText(mPlayerEdit[i].getText().toString());
                        }
                        mPlayerEdit[mPlayerNum - 1].setText("");
                        mPlayerEditArea[mPlayerNum - 1].setVisibility(View.GONE);
                        mPlayerAddButton.setImageResource(R.drawable.image_button_add);
                        mPlayerAddButton.setEnabled(true);
                        mPlayerNum--;
                    } else {
                        // プレイヤー削除の確認ダイアログ表示
                        showConfirmDeletePlayerDialog(pressedNum);
                    }
                }
            });
        }
    }

    /**
     * プレイヤー削除の確認ダイアログ表示
     * 
     * @param pressedNum プレイヤー番号
     */
    private void showConfirmDeletePlayerDialog(final int pressedNum) {

        AlertDialog.Builder dialog = new AlertDialog.Builder(NewCreate.this);
        dialog.setIcon(R.drawable.ic_menu_notice);
        dialog.setTitle(getResources().getString(R.string.dlg_delete_player_title));
        dialog.setMessage(String.format(getResources().getString(R.string.dlg_delete_player_msg),
                mPlayerEdit[pressedNum].getText().toString()));
        dialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

            public void onClick(final DialogInterface dialog, final int whichButton) {
                updatePlayerEditValue(pressedNum);
                SharedPreferences pref = getSharedPreferences(Util.PREF_DATA_SLOT[mSavedNumber],
                        MODE_PRIVATE);
                String[] playerScores = { pref.getString(PREF_DATA_KEY[8], ""),
                        pref.getString(PREF_DATA_KEY[9], ""),
                        pref.getString(PREF_DATA_KEY[10], ""),
                        pref.getString(PREF_DATA_KEY[11], "") };
                String[] playersPrKey = { PREF_DATA_KEY[8], PREF_DATA_KEY[9], PREF_DATA_KEY[10],
                        PREF_DATA_KEY[11] };
                Editor e = pref.edit();
                for (int i = pressedNum + 1; i < mPlayerNum; i++) {
                    e.putString(playersPrKey[i - 1], playerScores[i]);
                }
                e.putString(playersPrKey[mPlayerNum - 1], "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,");
                String[] playerNames = { pref.getString(PREF_DATA_KEY[4], ""),
                        pref.getString(PREF_DATA_KEY[5], ""), pref.getString(PREF_DATA_KEY[6], ""),
                        pref.getString(PREF_DATA_KEY[7], "") };
                String[] playerNamesKey = { PREF_DATA_KEY[4], PREF_DATA_KEY[5], PREF_DATA_KEY[6],
                        PREF_DATA_KEY[7], };
                for (int i = pressedNum + 1; i < mPlayerNum; i++) {
                    e.putString(playerNamesKey[i - 1], playerNames[i]);
                }
                e.commit();
                mPlayerNum--;
                mIsDeleted = true;
            }
        });
        dialog.setNegativeButton(android.R.string.no, null);
        dialog.create().show();
    }

    /**
     * @param pressedNum プレイヤー番号
     */
    private void updatePlayerEditValue(final int pressedNum) {

        mPlayerEdit[pressedNum].setText("");
        for (int i = pressedNum + 1; i < mPlayerNum; i++) {
            mHandicEdit[i - 1].setText(mHandicEdit[i].getText().toString());
            mPlayerEdit[i - 1].setText(mPlayerEdit[i].getText().toString());
        }
        mPlayerEdit[mPlayerNum - 1].setText("");
        mPlayerEditArea[mPlayerNum - 1].setVisibility(View.GONE);
        mPlayerAddButton.setImageResource(R.drawable.image_button_add);
        mPlayerAddButton.setEnabled(true);
    }

    /**
     * setupButtonAction
     */
    public void setupButtonAction() {

        // ラジオボタン押下時の動作
        setupRadioButtonAction(mRadioGroup);

        // プレイヤー追加ボタン押下時の動作
        setupPlayerAddButtonAction(mPlayerAddButton);

        // プレイヤー削除ボタン押下時の動作
        setupPlayerDeleteButtonAction(mPlayerDelButton);

        // 開始ボタン押下時の動作
        mStartButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(final View v) {
                startGolfScorer();
            }
        });
        // メモのトグルボタン押下時の動作
        mMemoToggleButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(final View v) {
                if (mIsMemoVisible) {
                    mMemoEdit.setVisibility(View.GONE);
                    mIsMemoVisible = false;
                } else {
                    mMemoEdit.setVisibility(View.VISIBLE);
                    mIsMemoVisible = true;
                }
            }
        });
        // 戻るボタン押下時の動作
        mMainExitButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(final View v) {
                finish();
            }
        });
    }

    /**
     * @return true:開始可 false:開始不可
     */
    private boolean checkEnableStart() {

        // =============================================================================
        // タイトル未入力の場合は開始しない対応
        if (mHoleTitle.trim().length() == 0) {
            Toast.makeText(getApplicationContext(),
                    getResources().getString(R.string.toast_input_title), Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        // =============================================================================
        // プレイヤー未入力の場合は開始しない対応
        if (mPersonNames[0].trim().length() == 0 && mPersonNames[1].trim().length() == 0
                && mPersonNames[2].trim().length() == 0 && mPersonNames[3].trim().length() == 0) {
            Toast.makeText(getApplicationContext(),
                    getResources().getString(R.string.toast_input_player), Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        // =============================================================================
        // 編集時にプレイヤー未入力があれば開始しない対応
        if (!mIsNewCreate) {
            for (int i = 0; i < mPlayerNum; i++) {
                if (mPersonNames[i].trim().length() == 0) {
                    Toast.makeText(getApplicationContext(),
                            getResources().getString(R.string.toast_input_player),
                            Toast.LENGTH_SHORT).show();
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * startGolfScorer
     */
    public void startGolfScorer() {

        mHoleTitle = mTitleEdit.getText().toString().replaceAll("<", "");
        mPersonNames[0] = mPlayerEdit[0].getText().toString().replaceAll("<", "");
        mPersonNames[1] = mPlayerEdit[1].getText().toString().replaceAll("<", "");
        mPersonNames[2] = mPlayerEdit[2].getText().toString().replaceAll("<", "");
        mPersonNames[3] = mPlayerEdit[3].getText().toString().replaceAll("<", "");
        mMemoText = mMemoEdit.getText().toString().replaceAll("<", "");
        mPersonHandi = getPersonHandiStr(mHandicEdit);
        mRoundCondit = mConditionSpinner.getSelectedItemPosition();

        // 開始しない条件を確認
        if (!checkEnableStart()) {
            return;
        }
        // 未記入のプレイヤーを詰める
        int tmp = 0;
        String[] strTmp = { "", "", "", "" };
        for (int i = 0; i < Util.MAX_PLAYER_NUM; i++) {
            if (mPersonNames[i].trim().length() != 0) {
                strTmp[tmp] = mPersonNames[i];
                tmp++;
            }
        }
        for (int i = 0; i < Util.MAX_PLAYER_NUM; i++) {
            mPersonNames[i] = strTmp[i];
        }
        // SharedPreferenceへ記録
        savePreference();

        if (mIsNewCreate) {
            startNewCreateActivity();
            return;
        }
        Toast.makeText(this, getResources().getString(R.string.toast_saved_settings),
                Toast.LENGTH_SHORT).show();
        finish();
        return;
    }

    /**
     * @param editText エディットテキスト
     * @return ハンデの文字列
     */
    private String getPersonHandiStr(final EditText[] editText) {
        if (editText == null || editText.length < 1) {
            return "";
        }
        StringBuilder strBuilder = new StringBuilder();

        for (int i = 0; i < editText.length; i++) {
            String str = editText[i].getText().toString();
            if (str.trim().length() < 1) {
                str = "0";
            }
            strBuilder.append(str);
            if (i < editText.length - 1) {
                strBuilder.append(",");
            }
        }
        return strBuilder.toString();
    }

    /**
     * startNewCreateActivity
     */
    private void startNewCreateActivity() {

        Intent intent = new Intent(getApplicationContext(), MainGolfScorer.class);
        GolfScoreData scoreData = Util.loadScoreDataFromPref(this, mSavedNumber);
        intent.putExtra("SAVED_NUMBER", mSavedNumber);
        intent.putExtra(GolfScoreData.EXTRAS_SEND_SCORE_DATA, scoreData);
        startActivity(intent);
        Toast.makeText(getApplicationContext(),
                getResources().getString(R.string.toast_created_new_data), Toast.LENGTH_SHORT)
                .show();
        finish();
    }

    /**
     * savePreference
     */
    private void savePreference() {

        SharedPreferences pref = getSharedPreferences(Util.PREF_DATA_SLOT[mSavedNumber],
                MODE_PRIVATE);
        Editor e = pref.edit();
        // 新規作成の時
        if (mIsNewCreate) {
            e.putString(PREF_DATA_KEY[0], String.valueOf(mSavedNumber)); // 保存データ番号
            e.putString(PREF_DATA_KEY[2], "1"); // 現在のホールナンバー
            e.putString(PREF_DATA_KEY[3], Util.DEFAULT_HOLEPAR_SCORE_STR); // 各ホールのパー値
            e.putString(PREF_DATA_KEY[8], Util.DEFAULT_PERSON_SCORE_STR); // プレイヤー１のスコア
            e.putString(PREF_DATA_KEY[9], Util.DEFAULT_PERSON_SCORE_STR); // プレイヤー２のスコア
            e.putString(PREF_DATA_KEY[10], Util.DEFAULT_PERSON_SCORE_STR); // プレイヤー３のスコア
            e.putString(PREF_DATA_KEY[11], Util.DEFAULT_PERSON_SCORE_STR); // プレイヤー４のスコア
            e.putString(PREF_DATA_KEY[15], Util.DEFAULT_IS_HOLE_LOCKED_STR); // 各ホールのロック状態
        }
        // ショートホール設定の確認
        if (mIsShortCheck.isChecked()) {
            String mShortSet = "3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,";
            e.putString(PREF_DATA_KEY[3], mShortSet);
        }
        e.putString(PREF_DATA_KEY[1], mHoleTitle); // タイトル
        e.putString(PREF_DATA_KEY[4], mPersonNames[0]); // プレイヤー名１
        e.putString(PREF_DATA_KEY[5], mPersonNames[1]); // プレイヤー名２
        e.putString(PREF_DATA_KEY[6], mPersonNames[2]); // プレイヤー名３
        e.putString(PREF_DATA_KEY[7], mPersonNames[3]); // プレイヤー名４
        e.putString(PREF_DATA_KEY[12], mMemoText); // メモ
        e.putString(PREF_DATA_KEY[13], mPersonHandi); // ハンデ
        if (mIs18hRound) {
            e.putString(PREF_DATA_KEY[14], "1"); // １８Ｈ設定
        } else {
            e.putString(PREF_DATA_KEY[14], "0"); // Out/In設定
        }
        e.putString(PREF_DATA_KEY[17], String.valueOf(mRoundCondit)); // コンディション
        e.commit();
    }

    @Override
    public boolean onKeyDown(final int keyCode, final KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (mIsDeleted) {
                startGolfScorer();
            } else {
                finish();
            }
            return true;
        }
        return false;
    }
}